<template> 
<div>
<el-cascader 
    :show-all-levels="false"
    placeholder="选择机构"
    :options="options"
    @input="handleSelect"
    filterable
    change-on-select
    :value="select"
>
</el-cascader>
</div>
</template>

<script>

import global_ from '@/common/Global'
import {doRequestPost,doRequestGet, doRequestPut, doRequestDel} from '@/utils/request'
export default {
    props: {
        value: {
            type: String,
            default: ''
        }
    },
    computed: {
    },
    created() {
        var self = this
        doRequestGet(global_.rest_path+'/auth/system/org/tree', {}).then(
            function(response) {
                //var res = response.data.results[0].children
                var res = response.Data[0].children
                res.forEach((v) => {
                    var node = self.transTree(v)
                    self.options.push(node)
                })

                if (self.value != ''){
                for(var idx= 0; idx < self.options.length; idx++) {
                    var target = self.makeValue(self.options[idx], self.value)
                    if (target.length > 0) {
                        self.select = target
                    } else {
                    }
                }
            }
            }
        )
    },
    data() {
        return  {
            options: [],
            select: []
        }
    },
    methods: {
        handleSelect(val) {
            this.$emit('input', val[val.length - 1])
        },
        transTree(data) {
            var self = this
            var node = {
                label: data.name+'(' + data.id + ')',
                value: data.id,
            }      
            var children = []
            if (data.children && data.children.length > 0) {
                data.children.forEach((v) => {
                    var subNode = self.transTree(v)
                    children.push(subNode)
                })
            }

            if (children.length > 0) {
                node.children = children
            }

            return node
        },
        makeValue(node, value) {
            var self = this
            if (node.value == value) {
                return [value]
            } else if (node.children &&node.children.length > 0) {
                for (var idx = 0; idx < node.children.length; idx++) {
                    var test = self.makeValue(node.children[idx], value)
                    if (test.length > 0) {
                        return [node.value].concat(test)
                    }
                }
            }

                return []
        }
    }
}


</script>